package logic

import (
	"encoding/json"
	"log"
	"mssgserver/constant"
	"mssgserver/db"
	"mssgserver/net"
	"mssgserver/server/common"
	"mssgserver/server/game/gameConfig"
	"mssgserver/server/game/model/data"
)

var CityFacilityService = &cityFacilityService{}

type cityFacilityService struct {
}

/*
*
初始化城市的基础设施
*/
func (c *cityFacilityService) TryCreate(cid, rid int, req *net.WsMsgReq) error {
	cityFacility := &data.CityFacility{}
	ok, err := db.Engine.Table(cityFacility).Where("cityId=?", cid).Get(cityFacility)
	if err != nil {
		log.Println("初始化城市的基础设施数据库报错")
		return common.New(constant.DBError, "初始化城市的基础设施数据库报错")
	}
	if ok {
		return nil
	}
	facilityConf := gameConfig.FacilityConf
	list := facilityConf.List
	facilities := make([]data.Facility, len(list))
	for i, conf := range list {
		ff := data.Facility{
			Name:         conf.Name,
			PrivateLevel: 0,
			Type:         conf.Type,
			UpTime:       0,
		}
		facilities[i] = ff
	}
	facilitiesStr, err := json.Marshal(facilities)
	if err != nil {
		log.Println("转json出错")
		return common.New(constant.DBError, "转json出错")
	}
	cityFacility.CityId = cid
	cityFacility.RId = rid
	cityFacility.Facilities = string(facilitiesStr)
	_, err = db.Engine.Table(cityFacility).Insert(cityFacility)
	if err != nil {
		log.Println("插入基础设施数据报错")
		return common.New(constant.DBError, "插入基础设施数据报错")
	}
	return nil
}
